package com.gsbelarus.gedemin.salary.util;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;

import com.gsbelarus.gedemin.lib.sync.protocol.etc.Parser;

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class WebServiceManager {

    public static final int CONNECTION_TIMEOUT = 10000;
    public static final int WAIT_RESPONSE_TIMEOUT = 15000;

    private HttpURLConnection httpURLConnection;

    public static void closeResourcesQuietly(Closeable... closeables) {  ///TODO move in IO helper
        for (Closeable c : closeables) {
            if (c != null) try {
                c.close();
            } catch (Exception ignored) {
            }
        }
    }

    public static boolean isNetworkReachable(Context context) {
        final ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = manager.getActiveNetworkInfo();
        if (activeNetworkInfo == null) {
            return false;
        }
        return (activeNetworkInfo.getState() == NetworkInfo.State.CONNECTED);
    }

    public static boolean hasNetworkConnection(Context context, String address) {
        final ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        final NetworkInfo activeNetworkInfo = manager.getActiveNetworkInfo();

        boolean connected = (null != activeNetworkInfo) && activeNetworkInfo.isConnected();
        if (!connected)
            return false;

        boolean routeExists;
        Socket s = null;
        try {
            InetAddress host = InetAddress.getByName(address);
            s = new Socket();
            s.connect(new InetSocketAddress(host, 53), 5000);
            routeExists = true;

            return (routeExists);
        } catch (IOException e) {
            return false;
        } finally {
            closeResourcesQuietly(s);
        }
    }

    public static String buildRequestUrl(String httpScheme, String serverAddress, Map<String, String> params)  {
        Uri.Builder requestParameterBuilder = new Uri.Builder();
        requestParameterBuilder.scheme(httpScheme)
                .encodedAuthority(serverAddress);
        for (Map.Entry<String, String> entry : params.entrySet()) {
            requestParameterBuilder.appendQueryParameter(entry.getKey(), entry.getValue());
        }

        return requestParameterBuilder.build().toString();
    }

    public Map<String, String> buildDefaultHeaders() {
        Map<String, String> headers = new HashMap<>();
        headers.put("Connection", "close");  // disable keep-alive
        headers.put("Content-Type", "text/xml; charset=utf-8");

        return headers;
    }

    public void openConnection(String serviceUrl) throws IOException {
        closeConnection();
        httpURLConnection = (HttpURLConnection) new URL(serviceUrl).openConnection();
    }

    public void closeConnection() {
        if (httpURLConnection != null) {
            httpURLConnection.disconnect();
            httpURLConnection = null;
        }
    }

    public void sendGetRequest(Map<String, String> headers) throws IOException {
        if (httpURLConnection != null) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                httpURLConnection.setRequestProperty(entry.getKey(), entry.getValue());
            }
            httpURLConnection.setDoInput(true);
            //httpURLConnection.setReadTimeout(CONNECTION_TIMEOUT);
            //httpURLConnection.setConnectTimeout(WAIT_RESPONSE_TIMEOUT);


            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.connect();
        }
    }

    public void sendPostRequest(byte[] requestData, Map<String, String> headers) throws IOException {
        if (httpURLConnection != null) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                httpURLConnection.setRequestProperty(entry.getKey(), entry.getValue());
            }
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setReadTimeout(CONNECTION_TIMEOUT);
            httpURLConnection.setConnectTimeout(WAIT_RESPONSE_TIMEOUT);

            OutputStream out = null;
            try {
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.connect();

                out = httpURLConnection.getOutputStream();
                if (out != null) {
                    out.write(requestData);
                    out.flush();
                }
            } finally {
                closeResourcesQuietly(out);
            }
        }
    }

    public int getResponseStatusCode() {
        if (httpURLConnection != null)
            try {
                return httpURLConnection.getResponseCode();
            } catch (IOException e) {
                return -1;
            }
        else
            return -1;
    }

    public String getResponse() {
        if (httpURLConnection != null && httpURLConnection.getDoInput())
            try {
                return convertStreamToString(httpURLConnection.getInputStream());
            } catch (IOException e) {
                return "";
            }
        else
            return "";
    }

    public boolean hasResponseStatusOK() {
        return getResponseStatusCode() == HttpURLConnection.HTTP_OK;
    }

    private String convertStreamToString(InputStream inputStream) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder sb = new StringBuilder();
        String line;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            return sb.toString();
        } finally {
            closeResourcesQuietly(reader);
        }
    }

    private List<String> convertStreamToStringList(InputStream inputStream) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "cp1251"));
        List<String> list = new ArrayList<>();
        String line;
        try {
            while ((line = reader.readLine()) != null) {
                list.add(line);
            }
            return list;
        } finally {
            closeResourcesQuietly(reader);
        }
    }

    public HashMap<String, String> parseResponse() throws IOException {
        if (httpURLConnection != null && httpURLConnection.getDoInput())
            return new Parser().parsingHeader(convertStreamToStringList(httpURLConnection.getInputStream()));
        else
            return new HashMap<>();
    }


    public HttpURLConnection getHttpURLConnection() {
        return httpURLConnection;
    }

    public void setHttpURLConnection(HttpURLConnection httpURLConnection) {
        this.httpURLConnection = httpURLConnection;
    }

}
